<template>
  <div class="card">
    <div style="padding:20px; font-size: large ;font-weight: bolder" v-if="data.user.role === 'USER'">我的贴子</div>
    <div style="padding:20px; font-size: large ;font-weight: bolder" v-if="data.user.role === 'ADMIN'">发贴空间</div>
    <div class="card" style="margin-bottom: 5px;">
      <el-input clearable @clear="load" style="width:240px; padding-right:5px" v-model="data.title"
                :prefix-icon="Search" placeholder="请输入贴子标题查询"></el-input>
      <el-select v-model="data.tableData.categoryId" placeholder="请选择贴子分类" @clear="load"
                 style="width: 240px">
        <el-option
            v-for="item in data.categoryData"
            :key="item.id"
            :label="item.title"
            :value="item.id"
        />
      </el-select>
      <el-button type="primary" @click="load" style="margin-left: 10px">查 询</el-button>
      <el-button type="danger" @click="reset">重 置</el-button>
    </div>
    <div class="card" style="margin-bottom: 5px;" v-if="data.user.role === 'USER'">
      <el-button type="primary" @click="handleAdd">发布贴子</el-button>
    </div>
    <el-table :data="data.tableData" border style="width: 100%"
              :header-cell-style="{ color:'#333', backgroundColor:'#fff',}" >
      <el-table-column type="index" label="索引" width="60px" />
      <el-table-column prop="image" label="封面" width="100px" >
        <template #default="scope">
          <el-image v-if="scope.row.img" :src="scope.row.img" :preview-src-list="[scope.row.img]" :preview-teleported="true"
                    style="width:40px; height:40px; border-radius:5px; display:block"/>
        </template>
      </el-table-column>
      <el-table-column prop="title" label="贴子标题"  />
      <el-table-column prop="categoryTitle" label="贴子分类"  />
      <el-table-column prop="content" label="贴子内容">
        <template v-slot="scope">
          <el-button type="primary" @click="viewContent(scope.row.content)">点击查看</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="time" label="贴子时间"  />
      <el-table-column prop="status" label="审核状态"  >
        <template v-slot="scope">
          <el-tag type="warning" v-if="scope.row.status === '待审核'">{{ scope.row.status }}</el-tag>
          <el-tag type="success" v-if="scope.row.status === '审核通过'">{{ scope.row.status }}</el-tag>
          <el-tag type="danger" v-if="scope.row.status === '审核不通过'">{{ scope.row.status }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="140">
        <template #default="scope" v-if="data.user.role === 'USER'">
          <el-button :disabled="scope.row.status !== '待审核'" type="primary" icon="Edit" circle @click="handleEdit(scope.row)"></el-button>
          <el-button :disabled="scope.row.status !== '待审核'" type="danger" icon="Delete" circle @click="del(scope.row.id)"></el-button>
        </template>
        <template #default="scope" v-if="data.user.role === 'ADMIN'">
          <el-button :disabled="scope.row.status !== '待审核'" type="primary" @click="handleEdit(scope.row)">审核</el-button>
          <el-button :disabled="scope.row.status !== '待审核'" type="danger" icon="Delete" circle @click="del(scope.row.id)"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <div>
      <el-pagination
          v-model:current-page="data.pageNum"
          v-model:page-size="data.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[5, 10, 20]"
          :total="data.total"
          @current-change="handlePageChange"
          @size-change="handleSizeChange"
      />
    </div>
    <!--发贴表单-->
    <el-dialog title="用户信息" v-model="data.formVisible" width="60%" destroy-on-close v-if="data.user.role === 'USER'">
      <el-form ref="formRef" :model="data.form" :rules="data.rules" label-position="right" label-width="80px" padding="20px 30px 20px 0">
        <el-form-item prop="title" label="贴子标题">
          <el-input v-model="data.form.title" autocomplete="off" placeholder="请输入贴子标题"/>
        </el-form-item>
        <el-form-item prop="categoryId" label="贴子分类">
          <el-select
              v-model="data.form.categoryId"
              placeholder="请选择贴子分类"
              size="large"
              style="width: 240px"
          >
            <el-option
                v-for="item in data.categoryData"
                :key="item.id"
                :label="item.title"
                :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="image">
          <el-upload
              action="http://localhost:9999/files/upload"
              :headers="{token: data.user.token}"
              list-type="picture"
              :on-success="handleFileSuccess">
            <el-button type="primary" >上传封面</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item prop="content" label="贴子详情">
          <div style="border: 1px solid #ccc; width: 100%">
            <Toolbar
                style="border-bottom: 1px solid #ccc"
                :editor="editorRef"
                :mode="mode"
            />
            <Editor
                style="height: 500px; overflow-y: hidden;"
                v-model="data.form.content"
                :mode="mode"
                :defaultConfig="editorConfig"
                @onCreated="handleCreated"
            />
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="data.formVisible = false">取 消</el-button>
          <el-button type="primary" @click="save">保 存</el-button>
        </div>
      </template>
    </el-dialog>
    <!--查看详情-->
    <el-dialog title="贴子信息" v-model="data.viewVisible" width="60%" destroy-on-close>
      <div v-html="data.content" style="margin:20px; width:60%"></div>
    </el-dialog>
    <!--审核表单-->
    <el-dialog title="申请信息" v-model="data.formVisible" width="500" destroy-on-close  v-if="data.user.role === 'ADMIN'">
      <el-form ref="formRef" :model="data.form" :rules="data.rules" label-position="right"
               label-width="80px" padding="20px 30px 20px 0">
        <el-form-item prop="status" label="审核状态">
          <el-radio-group v-model="data.form.status">
            <el-radio value="待审核" border>待审核</el-radio>
            <el-radio value="审核通过" border>审核通过</el-radio>
            <el-radio value="审核不通过" border>审核不通过</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="reason" label="审核理由" style="margin-top:20px" v-if="data.form.status === '审核不通过'">
          <el-input v-model="data.form.reason" autocomplete="off" placeholder="请输入不通过理由" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="data.formVisible = false">取 消</el-button>
          <el-button type="primary" @click="save">保 存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {Search} from "@element-plus/icons-vue";
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import {onBeforeUnmount, reactive, ref, shallowRef} from "vue";
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import request from "@/utils/request.js";
import {ElMessage, ElMessageBox} from "element-plus";

const formRef = ref()

const data = reactive({
  user:JSON.parse(localStorage.getItem('code_user') || '{}'),
  pageNum: 1,
  pageSize: 5,
  total: 0,
  tableData: [],
  content:null,
  viewVisible: false,
  formVisible: false,
  form: {},
  title: null,
  img: null,
  categoryId: null,
  categoryData:[],
  rules:{
    title:[{required: true, message:"请输入贴子标题", trigger:"blur"},
      {min: 5,required: true, message:"标题最少五个字", trigger:"blur"}],
    content:[{required: true, message:"请输入贴子内容", trigger:"blur"}],
    categoryId:[{required: true, message:"请选择贴子分类", trigger:"blur"}],
  }
})

/* wangEditor5 初始化开始 */
const editorRef = shallowRef()  // 编辑器实例，必须用 shallowRef
const mode = 'default'
const editorConfig = { MENU_CONF: {} }
// 图片上传配置
editorConfig.MENU_CONF['uploadImage'] = {
  headers: {
    token: data.user.token,
  },
  server: 'http://localhost:9999/files/wang/upload',  // 服务端图片上传接口
  fieldName: 'file'  // 服务端图片上传接口参数
}
// 组件销毁时，也及时销毁编辑器，否则可能会造成内存泄漏
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})
// 记录 editor 实例，重要！
const handleCreated = (editor) => {
  editorRef.value = editor
}
/* wangEditor5 初始化结束 */

const load = () => {
  request.get("/written/selectPage", {
    params: {
      pageNum: data.pageNum,
      pageSize: data.pageSize,
      title: data.title,
      categoryId: data.tableData.categoryId
    }
  }).then(res => {
    if (res.code === '200') {
      data.tableData = res.data?.list;
      data.total = res.data?.total;
    }else{
      ElMessage.error(res.msg)
    }
  })
}
load()

const reset = () => {
  data.title = null
  data.form.categoryId = null
  load()
}

const handleAdd = () => {
  data.form = {};
  data.formVisible = true;
}

const handleEdit = (row) => {
  data.form = JSON.parse(JSON.stringify(row))
  data.formVisible = true
}

const handlePageChange = (newPageNum) => {
  data.pageNum = newPageNum;
  load()
}

const handleSizeChange = (newPageSize) => {
  data.pageSize = newPageSize
  data.pageNum = 1;
  load()
}

const handleFileSuccess = (res) => {
  data.form.img = res.data
}

const viewContent = (content) => {
  data.content = content
  data.viewVisible = true
}

const del = (id) => {
  ElMessageBox.confirm("删除后无法恢复，您确定要删除该贴子吗？", "删除确认窗口", {type: "warning"})
  .then(res => {
    request.delete(`/written/delete/${id}`).then(res => {
      if (res.code === '200') {
        ElMessage.success("删除成功")
        load()
      }else{
        ElMessage.error(res.msg)
      }
    })
  }).catch(err => {})
}

const add = () => {
  request.post("/written/add", data.form).then(res => {
    if (res.code === '200') {
      ElMessage.success("发帖成功")
      data.formVisible = false;
      load()
    }else{
      ElMessage.error(res.msg)
    }
  })
}

const update = () => {
  request.put("/written/update", data.form).then(res => {
    if (res.code === '200') {
      ElMessage.success("修改成功")
      data.formVisible = false;
      load()
    }else{
      ElMessage.error(res.msg)
    }
  })
}

const save = () => {
  formRef.value.validate(value => {
    if (value) {
      data.form.id ? update() : add()
    }
  })
}

const loadCategory = () => {
  request.get('/category/selectAll').then(res => {
    if (res.code === '200') {
      data.categoryData = res.data
    }else{
      ElMessage.error(res.msg)
    }
  })
}
loadCategory()
</script>